package com.itheima.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Code;
import com.itheima.common.DishConstant;
import com.itheima.common.MessageConstant;
import com.itheima.dto.DishDTO;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ding
 * @version 1.0
 * @description: TODO 菜品管理
 * @date 2022/6/5 14:51
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

/**
 * 功能描述 :菜品列表查询
 * @param page
 * @param pageSize
 * @param name
 * @return : com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.itheima.domain.Dish>
 */
    @Override
    public Page<Dish> page(Integer page, Integer pageSize, String name) {
        //校验参数
        if (page < 1) {
            page = 1;
        }
        if (pageSize < 1) {
            pageSize = 10;
        }
        Page<Dish> pageDish = new Page<>(page, pageSize);
        //拼接查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Dish::getUpdateTime);
        wrapper.eq(Dish::getIsDeleted, DishConstant.IS_NOT_DELETED);
        if (name != null) {
            wrapper.like(Dish::getName, name);
        }
        //执行查询
        Page<Dish> selectPage = dishMapper.selectPage(pageDish, wrapper);
        //遍历每个菜品，根据菜品中分类ID，获取分类名称
        List<Dish> records = selectPage.getRecords();
        for (Dish record : records) {
            // 根据Dish对象中的categoryId，查询分类对象
            Long categoryId = record.getCategoryId();
            Category category = categoryMapper.selectById(categoryId);
            //获取分类对象中分类名称，复制给Dish菜品对象的categoryName字段
            String categoryName = category.getName();
            record.setCategoryName(categoryName);
        }

        return selectPage;
    }

/**
 * 功能描述 : 新增菜品
 * @param dishDTO
 * @return : int
 */
    @Transactional
    @Override
    public int save(DishDTO dishDTO) {
        int row = 0;
        //判断是否为空
        if (dishDTO==null){
            return  row;
        }
        String name = dishDTO.getName();
        //判断菜品名称是否为NULL
        if (name==null){
            return row;
        }
        name = name.trim();
        //用ASCII判断名字是否有特殊字符数字
/*        char[] chars = name.toCharArray();
        for (char aChar : chars) {
            int a = aChar;
            if (a>=0&&a<256){
                throw new BusinessException(Code.ERROR,MessageConstant.DISH_ANOMALY_SUCCESS);
            }
        }*/
        //用hutool工具类判断名字是否有特殊字符数字
        if (!Validator.isChinese(name)){
            throw new BusinessException(Code.ERROR,MessageConstant.DISH_ANOMALY_SUCCESS);
        }
        //判断菜品名称是否重复
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getName,name.trim());
        Dish dish = dishMapper.selectOne(wrapper);
        if (dish!=null){
            return row;
        }
        //判断菜品名称的长度
        if (name.length()>20){
            return row;
        }
        //判断金额是否为null
        BigDecimal price = dishDTO.getPrice();
        if (price==null){
            return row;
        }
        //校验菜品描述长度
        int length = dishDTO.getDescription().length();
        if (length>200){
            return row;
        }
        //校验图片是否为NULL、是否6中为图片格式
        String dtoImage = dishDTO.getImage();
        if (dtoImage==null){
            return row;
        }
        String extension = dtoImage.substring(dtoImage.lastIndexOf(".") + 1);
        if (extension.equals("jpg")||extension.equals("png")||extension.equals("gif")||extension.equals("bmp")||extension.equals("jpeg")||extension.equals("image")) {
            //新增菜品对象
            Dish dish1 = new Dish();
            //把前端传递的参数拷贝到菜品对象中
            BeanUtils.copyProperties(dishDTO, dish1);
            row = dishMapper.insert(dish1);
            if (row < 1) {
                return row;
            }
            //保存菜品、一个菜品可能会产生多个口味信息
            //判断口味数据是否存在，存在则继续执行，否-直接返回结果即可（备注：口味数据不是必填字段）
            List<DishFlavor> flavors = dishDTO.getFlavors();
            if (flavors == null) {
                return row;
            }
            //菜品新增成功后，即可获取菜品ID
            Long dishID = dish1.getId();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishID);
                dishFlavorMapper.insert(flavor);
            }
        }else {
            throw new BusinessException(Code.ERROR,MessageConstant.DISH_PICTURE_SUCCESS);

        }

        return row;
    }
    /**
     * 功能描述: 根据categoryId查询菜品信息,返回到添加套餐的添加菜品页面
     *
     * @param categoryId
     * @return : java.util.List<com.itheima.entity.Dish>
     */
    @Override
    public List<DishDTO> findByCategoryId(Long categoryId, String name) {

        List<DishDTO> dishes = new ArrayList<>();
        if (categoryId == null && name == null) {
            return dishes;
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        if (categoryId != null) {
            queryWrapper.eq(Dish::getCategoryId, categoryId);
        }
        if (name != null) {
            queryWrapper.like(Dish::getName, name.trim());
        }
        queryWrapper.eq(Dish::getIsDeleted,DishConstant.IS_NOT_DELETED);
        queryWrapper.eq(Dish::getStatus,DishConstant.SELL);
        //2.执行查询,获取菜品列表
        List<Dish> dishList = dishMapper.selectList(queryWrapper);

        //3.遍历菜品列表，获取每个菜品的口味列表
        for (Dish dish : dishList) {
            DishDTO dishDTO = new DishDTO();
            //3.1 把菜品中属性，拷贝到DishDTO对象中（注意：source源数据对象、target目标数据对象，需要名称、类型一致才能拷贝）
            BeanUtils.copyProperties(dish, dishDTO);
            //3.2 根据菜品ID，获取菜品口味列表
            LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
            dishFlavorWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(dishFlavorWrapper);
            //3.3 把口味列表数据存入DishDTO对象中
            dishDTO.setFlavors(dishFlavors);
            //3.4 把DishDTO
            dishes.add(dishDTO);
        }
        return dishes;

    }
/**
 * 功能描述 :获取菜品信息回显
 * @param id
 * @return : com.itheima.dto.DishDTO
 */
    @Override
    public DishDTO findById(Long id) {
        //校验参数
        if (id==null){
            return null;
        }
        //根据菜品ID，查询菜品对象
        Dish dish = dishMapper.selectById(id);
        if (dish==null){
            return null;
        }
        // 把“菜品对象”中属性，拷贝到 DishDTO；把“菜品口味列表”赋值给DishDTOflavors
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish,dishDTO);
        //3.根据菜品ID，查询菜品口味列表
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorMapper.selectList(wrapper);
        if (flavors!=null){
           dishDTO.setFlavors(flavors);
        }
        return dishDTO;
    }
/**
 * 功能描述 :修改菜品信息
 * @param dishDTO
 * @return : int
 */
    @Transactional
    @Override
    public int update(DishDTO dishDTO) {
      int row = 0;
      if (dishDTO==null){
          return row;
      }
        //校验菜品名称是否为NULL、是否符合菜品名称格式、长度
        String name = dishDTO.getName();
        if (name==null){
            return row;
        }
        if (name.length()>20){
            return row;
        }
        name = name.trim();
        if (!Validator.isChinese(name)){
            throw new BusinessException(Code.ERROR,MessageConstant.DISH_ANOMALY_SUCCESS);
        }
      //判断菜品名称是否重复
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getName,name);
        //查询菜品名称是否重复
        wrapper.ne(Dish::getId,dishDTO.getId());
        Dish dish = dishMapper.selectOne(wrapper);
        if (dish!=null){
            throw new BusinessException(Code.ERROR, MessageConstant.DISH_ERROR_SUCCESS);
        }
        //用ASCII判断名字是否有中文字符数字
/*        char[] chars = name.toCharArray();
        for (char aChar : chars) {
            int a = aChar;
            if (a>=0&&a<256){
                 throw new BusinessException(Code.ERROR,MessageConstant.DISH_ANOMALY_SUCCESS);

            }
        }*/
        //判断金额是否为null
        BigDecimal price = dishDTO.getPrice();
        if (price==null){
            return row;
        }
        //校验菜品描述长度
        int length = dishDTO.getDescription().length();
        if (length>200){
            return row;
        }
        //校验图片是否为NULL、是否为图片格式
        String dtoImage = dishDTO.getImage();
        if (dtoImage==null){
            return row;
        }

        //2.修改菜品信息
        Dish dish1 = new Dish();
        BeanUtils.copyProperties(dishDTO, dish1);
        row = dishMapper.updateById(dish1);
        if (row < 1) {
            return row;
        }
        //删除口味
        LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DishFlavor::getDishId, dish1.getId());
       dishFlavorMapper.delete(wrapper1);
//        判断口味数据是否存在，存在则继续执行
        //新增口味
        if (dishDTO.getFlavors() != null) {
            List<DishFlavor> flavors = dishDTO.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish1.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
        return row;
    }
/**
 * 功能描述 :删除菜品
 * @param ids
 * @return : int
 */
@Transactional
    @Override
    public int deleteByIds(Long[] ids) {
    //逻辑删除
            // 构建更新条件
				 LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(Dish::getIsDeleted, DishConstant.IS_DELETED);
				wrapper.in(Dish::getId,ids);
				//2.执行更新操作
				int row = dishMapper.update(new Dish(), wrapper);

        return row;
    }
/**
 * 功能描述 :修改状态
 * @param status 
 * @param ids
 * @return : void 
 */
    @Transactional
    @Override
    public void updateStatusByIds(Integer status, Long[] ids) {
        //.构建更新条件
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus,status);
        wrapper.in(Dish::getId,ids);
        //执行更新操作
        dishMapper.update(new Dish(),wrapper);
    }
}
